package com.nbsaas.boot.data.ext.resource;

import com.nbsaas.boot.data.api.apis.QueryMacroApi;
import com.nbsaas.boot.data.api.domain.request.QueryMacroSearch;
import com.nbsaas.boot.data.api.domain.simple.QueryMacroSimple;
import com.nbsaas.boot.data.ext.apis.FreemarkerMacroLoader;
import com.nbsaas.boot.rest.response.ListResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 宏加载功能
 *
 */
@Component
public class FreemarkerMacroLoaderResource implements FreemarkerMacroLoader {


    private final Map<Integer, String> macroMap = new ConcurrentHashMap<>();

    private final Map<Integer, Boolean> macroState = new ConcurrentHashMap<>();


    @Resource
    private QueryMacroApi queryMacroApi;


    @Override
    public String macro() {
        return macro(1);
    }

    @Override
    public String macro(Integer type) {
        Boolean state = macroState.get(type);
        if (state == null || !state) {
            reload(type);
        }
        return macroMap.getOrDefault(type, "");
    }

    @Override
    public void reload() {
        reload(1);
    }

    @Override
    public void reload(Integer type) {
        macroState.put(type, true);
        QueryMacroSearch search = new QueryMacroSearch();
        search.setMacroType(type);
        ListResponse<QueryMacroSimple> macros = queryMacroApi.list(search);
        if (macros.getCode() != 200) {
            return;
        }
        List<QueryMacroSimple> list = macros.getData();
        if (list == null){
            return;
        }
        StringBuilder sb = new StringBuilder();
        for (QueryMacroSimple item : list) {
            if (StringUtils.hasText(item.getContent())) {
                sb.append(item.getContent()).append("\n");
            }
        }
        macroMap.put(type, sb.toString());
    }


}
